const url = require('url')

function acceptsHtml (head, accepts) {
    for (let i = 0; i < accepts.length; i++) {
        if (head.indexOf(accepts[i]) !== -1) return true
    }

    return false
}

module.exports = function (index = 'index.html') {
    return async (ctx, next) => {
        if (ctx.method !== 'GET') return await next()
        if (!ctx.headers || typeof ctx.headers.accept !== 'string') return await next()
        if (ctx.headers.accept.indexOf('application/json') === 0) return await next()
        if (!acceptsHtml(ctx.headers.accept, ['text/html', '*/*'])) return await next()

        const uri = new url.URL(ctx.url, 'http://localhost')

        if (uri.pathname.lastIndexOf('.') > uri.pathname.lastIndexOf('/')) {
            return await next()
        }

        ctx.path = '/' + index

        await next()
    }
}
